
/*-------------------------------------------------------------------------
 *
 * dict_int.c
 *	  整数的文本搜索词典
 *
 * Copyright (c) 2007-2022, PostgreSQL Global Development Group
 *
 * IDENTIFICATION
 *	  contrib/dict_int/dict_int.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "commands/defrem.h"
#include "tsearch/ts_public.h"

PG_MODULE_MAGIC;

typedef struct
{
	int			maxlen;
	bool		rejectlong;
	bool		absval;
} DictInt;


PG_FUNCTION_INFO_V1(dintdict_init);
PG_FUNCTION_INFO_V1(dintdict_lexize);

Datum dintdict_init(PG_FUNCTION_ARGS)
{
	List	   *fc_dictoptions = (List *) PG_GETARG_POINTER(0);
	DictInt    *fc_d;
	ListCell   *fc_l;

	fc_d = (DictInt *) palloc0(sizeof(DictInt));
	fc_d->maxlen = 6;
	fc_d->rejectlong = false;
	fc_d->absval = false;

	foreach(fc_l, fc_dictoptions)
	{
		DefElem    *fc_defel = (DefElem *) lfirst(fc_l);

		if (strcmp(fc_defel->defname, "maxlen") == 0)
		{
			fc_d->maxlen = atoi(defGetString(fc_defel));

			if (fc_d->maxlen < 1)
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("maxlen value has to be >= 1")));
		}
		else if (strcmp(fc_defel->defname, "rejectlong") == 0)
		{
			fc_d->rejectlong = defGetBoolean(fc_defel);
		}
		else if (strcmp(fc_defel->defname, "absval") == 0)
		{
			fc_d->absval = defGetBoolean(fc_defel);
		}
		else
		{
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("unrecognized intdict parameter: \"%s\"",
							fc_defel->defname)));
		}
	}

	PG_RETURN_POINTER(fc_d);
}

Datum dintdict_lexize(PG_FUNCTION_ARGS)
{
	DictInt    *fc_d = (DictInt *) PG_GETARG_POINTER(0);
	char	   *fc_in = (char *) PG_GETARG_POINTER(1);
	int			fc_len = PG_GETARG_INT32(2);
	char	   *fc_txt;
	TSLexeme   *fc_res = palloc0(sizeof(TSLexeme) * 2);

	fc_res[1].lexeme = NULL;

	if (fc_d->absval && (fc_in[0] == '+' || fc_in[0] == '-'))
	{
		fc_len--;
		fc_txt = pnstrdup(fc_in + 1, fc_len);
	}
	else
		fc_txt = pnstrdup(fc_in, fc_len);

	if (fc_len > fc_d->maxlen)
	{
		if (fc_d->rejectlong)
		{
			/* 通过返回空数组进行拒绝 */
			pfree(fc_txt);
			fc_res[0].lexeme = NULL;
		}
		else
		{
			/* 修剪整数 */
			fc_txt[fc_d->maxlen] = '\0';
			fc_res[0].lexeme = fc_txt;
		}
	}
	else
	{
		fc_res[0].lexeme = fc_txt;
	}

	PG_RETURN_POINTER(fc_res);
}
